package com.easy.admin.system.test.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangbo
 * @deprecated netty server for chat  handler
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static List<Channel> channels = new ArrayList<Channel>();

    /**
     * //接收服务端的消息
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel channel = channelHandlerContext.channel();
        for(Channel ch:channels){
            if(channel!=ch) {
                ch.writeAndFlush(channel.remoteAddress().toString().substring(1) + "说：" + s);
            }
        }
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
        System.out.println(ctx.channel().remoteAddress().toString().substring(1)+"上线了");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channels.remove(ctx.channel());
        System.out.println(ctx.channel().remoteAddress().toString().substring(1)+"下线了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }
}
